/*
 * FileName: SocketHandler.java
 * Author:   zzw
 * Date:     2018年05月23日
 * Description:
 */
package com.zzw.basic.io.nio.handler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.CountDownLatch;

/**
 * 〈〉<br>
 * 〈〉
 *
 * @author zzw
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本]（可选）
 */
public class BIOSocketHandler implements Runnable{
    private CountDownLatch countDownLatch;
    private SocketChannel socketChannel;

    public BIOSocketHandler(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    public BIOSocketHandler(CountDownLatch countDownLatch, SocketChannel socketChannel) {
        this.countDownLatch = countDownLatch;
        this.socketChannel = socketChannel;
    }

    @Override
    public void run() {
        for (int i = 0;i < 10;i++){
            // 发送请求
            ByteBuffer buffer = ByteBuffer.wrap("1234567890".getBytes());
            try {
                socketChannel.write(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 读取响应
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            int num;
            try {
                if ((num = socketChannel.read(readBuffer)) > 0) {
                    readBuffer.flip();

                    byte[] re = new byte[num];
                    readBuffer.get(re);

                    String result = new String(re, "UTF-8");
                    System.out.println("返回值: " + result);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        countDownLatch.countDown();
    }
}
